<?php

/**
 * Created by PhpStorm.
 * User: zcw 812039610@qq.com
 * Date: 2019/7/9
 * Time: 11:30
 */

namespace scripts;

use globalunit\logic\Web3DLogic;
use globalunit\logic\UserLogic;
use globalunit\utils\GenID;
use QYS\Protocol\Response;
use QYS\Protocol\Request;
use QYS\Db\Mysql;
use QYS\Db\Mongo;
use QYS\Db\Redis;
use QYS\Log\Log;
use globalunit\utils\Config;
use globalunit\utils\KeysUtil;
use globalunit\utils\JWTUtil;
use QYS\Core\Config  as CoreConfig;
use globalunit\utils\TxSMS;

class CMDLOGIN
{

    public static function sendcode($request, $response, $rediscli)
    {
        $appid = $request->getString("appid");
        $phone = $request->getString('phone');
        if (!isset($appid) || !isset($phone)) {
            return ["errcode" => 10001,];
        }

        $res = Web3DLogic::getWeb3dByAppid($appid);
        if (empty($res)) {
            return ["errcode" => 10006];
        }

        //活动未开始
        if(strtotime($res["start_time"]) > time()){
            return ["errcode" => 101];
        }

        //活动已结束
        if(strtotime($res["end_time"]) < time()){
            return ["errcode" => 102];
        }

        $key = KeysUtil::get_phonecode_key($phone);
        $code = $rediscli->get($key);
        if (!empty($code)) {
            return ['errcode' => 10003,];
        }
        $code = rand(1000, 9999);
        $sms = new TxSMS();
        $ok = $sms->sendcode($phone, $code);
        if ($ok) {
            $rediscli->set($key, $code);
            $rediscli->expire($key, 60 * 5);
        } else {
            return ['errcode' => 10004,];
        }
        return ['errcode' => 0];

    }

    public static function login($request, $response, $rediscli)
    {
        $appid = $request->postString("appid");
        $phone = $request->postString("phone");
        $code = $request->postString("code");
        if (empty($appid) || empty($phone) || empty($code)) {
            return ["errcode" => 10001];
        }

        $res = Web3DLogic::getWeb3dByAppid($appid);
        Log::var_dump($res);
        if (empty($res)) {
            return ["errcode" => 10006];
        }
        //活动未开始
        if(strtotime($res["start_time"]) > time()){
            return ["errcode" => 101];
        }

        //活动已结束
        if(strtotime($res["end_time"]) < time()){
            return ["errcode" => 102];
        }

        //TODO 验证码验证
        $debug = CoreConfig::get("debug");
        if(!$debug){
            $key = KeysUtil::get_phonecode_key($phone);
            $savecode = $rediscli->get($key);
            if ($savecode != $code) {
                return ['errcode' => 10005,];
            }
            $rediscli->del($key);
        }

        $user = UserLogic::loaduserbyphone($appid, $phone);
        if (empty($user)){
            $data = [
                'phone' => $phone,
                "organize_id" => $res['organize_id'],
                "appid" =>  $appid,
                "pfid" => $res["pfid"]
            ];
            $user = UserLogic::register($rediscli, $data);
            if (empty($user)) {
                return ["errcode" => 10003];
            }
        }else{
            $ok = UserLogic::login($user['id']);
            if (!$ok){
                return ['errcode' => 10010, 'errmsg' => "登录失败, 请稍后再试!"];
            }
        }
        $token = GenID::gen();
        $tokenkey = KeysUtil::get_main_token($user['id']);
        $rediscli->set($tokenkey, $token);
        $GAMENAME =  $GLOBALS['GAMENAME'];
        $VERSION =  $GLOBALS['VERSION'];
        $jwt = JWTUtil::encode(array("id" => $user['id'], "appid" => $appid, "token" => $token), "$GAMENAME-$VERSION", 'HS256');
        return ['errcode' => 0, "data" => ["user" => $user, "jwt" => $jwt]];
    }


    public static function autologin($request, $response, $rediscli)
    {
        $id = $request->getString("id");
        if (empty($id)) {
            return ["errcode" => 10001];
        }
        $user = UserLogic::loaduser($id);
        if (empty($user)) {
            return ["errcode" => 10007];
        }
        $ok = UserLogic::login($user['id']);
        if (!$ok){
            return ['errcode' => 10010, 'errmsg' => "登录失败, 请稍后再试!"];
        }
        return ['errcode' => 0, "data" => ["user" => $user]];
    }
}

class LoginCtrl
{

    public function invoke($request, $response, $params)
    {
        $response->addHeader("Content-Type", 'application/json');
        $response->addHeader("Access-Control-Allow-Origin", "*");
        $response->addHeader("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
        $response->addHeader('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept");
        $response->sendHttpHeader();
        $fname = $params['fname'];
        $rediscli = Redis::getInstance("redis1");
        $result = null;
        $result = CMDLOGIN::$fname($request, $response, $rediscli);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $errcode = $result['errcode'];
            if (!isset($result['errmsg'])) {
                $result['errmsg'] = Config::get('errmsg', 'e' . $errcode);
            }
        }
        Log::info('debug', $request, ['fname' => $fname, 'result' => $result]);
        $response->say(json_encode($result));
    }
}
